package mysql

import (
	"bluebell-backend/common"
	"bluebell-backend/model/po"
	"fmt"
)

func Insert(user *po.User) int {
	err := db.Create(user).Error
	if err != nil {
		return common.ERROR
	}
	return common.SUCCESS
}

func GetOneUserByEmail(email string) (*po.User, error) {
	user := new(po.User)
	err := db.Where("email = ?", email).First(user).Error
	if err != nil {
		return nil, err
	}
	return user, nil
}

func GetOneByUUID(uuid int64) (*po.User, error) {
	user := new(po.User)
	err := db.Where("uuid = ?", uuid).First(user).Error
	if err != nil {
		return nil, err
	}
	return user, nil

}

func UpdateByUUID(user *po.User, uuid int64) (int, error) {
	err := db.Model(user).Where("uuid = ?", uuid).Updates(po.User{
		Username: user.Username,
		Nickname: user.Nickname,
		// TODO 头像
	}).Error
	if err != nil {
		return common.ERROR, err
	}
	return common.SUCCESS, nil
}

// 批量查询
func MQueryUserById(ids []int64) (map[int64]*po.User, error) {
	var users []*po.User
	if err := db.Where("uuid in (?)", ids).Find(&users).Error; err != nil {
		fmt.Println("批量查询失败")
		return nil, err
	}
	userMap := make(map[int64]*po.User)
	for _, user := range users {
		userMap[user.UUID] = user
	}
	return userMap, nil
}

// 判断用户是否重复
func CheckIsRepeat(email string) bool {
	var user po.User
	db.Select("id").Where("email = ?", email).First(&user)
	fmt.Println(user)
	if user.ID > 0 {
		return true
	}
	return false

}
